import { define } from 'cydon'
import { Technology } from '../type'
import { CTable } from './CTable'
import { processData } from '../util'
import { CPagination } from './CPagination'
import { DataFilter } from './DataFilter'
import { techs } from '../defs'
import { world } from '../store'
import { queue } from './QTable'
import view from '../view'
import { error } from '@cydon/ui/Message'
import { getTile } from '../game'

/**
 * @element tech-tree
 * 科技树
 */
@define('tech-tree')
export class TechTree extends CTable<Technology> {
	static observedAttributes = super.observedAttributes

	/** 是否可以解锁 */
	canUnlock(item: Technology) {
		const unlocked = world.techs
		return !unlocked.has(item.name) &&
			item.prereqs.every(name =>
				this.items.some(i => i.name == name && unlocked.has(i.name)))
	}

	async updateContents(p: CPagination, f?: DataFilter) {
		this.items = processData(techs, p, f)
	}

	/** 解锁科技 */
	unlock(item: Technology) {
		const slot = view.selectedSlot
		const id = getTile(slot)[2]
		if (id == 33 && (id >= 122 || id <= 124)) {
			// TODO: 解锁科技消耗
			queue({
				name: '研究' + item.name,
				desc: '',
				slot,
				remainTime: item.time,
				recipeId: -1,
				value: -1
			})
			this.updateValue('item')
		} else
			error('请先选择一个研究设施')
	}

	/** 是否已解锁 */
	unlocked(item: Technology) {
		return world.techs.has(item.name)
	}
}

const [techTree] = document.getElementsByTagName('tech-tree')

/** 更新科技树 */
export function updateTechs() {
	techTree.updateContents(techTree.page, techTree.filter)
}

declare global {
	interface HTMLElementTagNameMap {
		'tech-tree': TechTree
	}
}
